package us.versus.them.weeds.constraints;

import flash.display.Graphics;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.Lib;

import us.versus.them.weeds.Vertlet;

class Segment implements Constraint {
	public var start:Vertlet;
	public var stop:Vertlet;
	var distance:Float;
	var mass:Float;

	var start_mass_ratio:Float;
	var stop_mass_ratio:Float;

	public function new( start:Vertlet, stop:Vertlet ) {
		this.set( start, stop );
	}

	public function set( start:Vertlet, stop:Vertlet ) {
		this.start = start;
		this.stop = stop;
		this.distance = this.currentDistance();
		this.mass = start.mass + stop.mass;
		this.start_mass_ratio = 1 - ( start.mass / this.mass );
		this.stop_mass_ratio  = 1 - ( stop.mass / this.mass );
	}

	public inline function currentDistance() {
		return Point.distance( stop.current, start.current );
	}

	public function enforce() {
		var currentDistance = this.currentDistance();
		if ( 0 != currentDistance ) {

			var diff = ( currentDistance - this.distance ) / currentDistance;
			var xdiff = ( stop.current.x - start.current.x ) * diff;
			var ydiff = ( stop.current.y - start.current.y ) * diff;

			start.current.x += xdiff * this.start_mass_ratio;
			start.current.y += ydiff * this.start_mass_ratio;

			stop.current.x  -= xdiff * this.stop_mass_ratio;
			stop.current.y  -= ydiff * this.stop_mass_ratio;
		}  
	}

	public function normal() : Point {
		var normal = new Point(
			  ( stop.current.y - start.current.y )
			, ( start.current.x - stop.current.x )
		);
		normal.normalize( 1 );
		return normal;
	}
}
